package javacommon.base;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javacommon.util.ConvertRegisterHelper;
import javacommon.util.FileUtils;
import javacommon.web.page.Page;
import javacommon.web.page.PageRequest;
import javacommon.web.util.ServletRequestUtils;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.beanutils.BeanUtilsBean;
import org.lanqiao.webfm.sys.SysConfig;
import org.lxh.smart.File;
import org.lxh.smart.SmartUpload;
import org.lxh.smart.SmartUploadException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 所有Servlet应该继承的基类
 * 
 * @author zhengwei lastmodified 2013年9月7日
 * 
 */
public abstract class BaseServlet extends HttpServlet {
	protected static Logger logger = LoggerFactory.getLogger(BaseServlet.class);
	private static final long serialVersionUID = 1L;

	protected static BeanUtilsBean beanUtils = new BeanUtilsBean();
    static {
    	//用于注册日期类型的转换
    	String[] datePatterns = new String[] {"yyyy-MM-dd","yyyy-MM-dd HH:mm:ss","yyyy-MM-dd HH:mm:ss.SSS","HH:mm:ss"};
    	ConvertRegisterHelper.registerConverters(beanUtils.getConvertUtils(),datePatterns);
    }
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}
	/**
	 * 根据url的后缀，调用不同的方法，这样，一个Servlet可以同时处理增删改查业务，而不必为每个业务单独建立一个Servlet<br>
	 * 禁止子类覆盖
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		// 根据url的后缀，调用不同的方法，这样，一个Servlet可以同时处理增删改查业务，而不必为每个业务单独建立一个Servlet
		// 客户端提供的URL应该类似这样：/RightsUserServlet/list.do
		String uri = request.getRequestURI();
		try {
			if (uri.endsWith("list.do")) {
				doListInternal(request, response);
			} else if (uri.endsWith("delete.do")) {
				doDeleteInternal(request, response);
			} else if (uri.endsWith("edit.do")) {
				doEditInternal(request, response);
			} else if (uri.endsWith("update.do")) {
				doUpdateInternal(request, response);
			} else if (uri.endsWith("create.do")) {
				doCreateInternal(request, response);
			} else if (uri.endsWith("save.do")) {
				doSaveInternal(request, response);
			} else if (uri.endsWith("show.do")) {
				doShowInternal(request, response);
			} /*else {
				response.sendError(404);
			}*/
		} catch (SQLException e) {
			logger.error(e.getMessage(), e);
			throw new RuntimeException(e);
		}
	}

	

	protected abstract void doShowInternal(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException, SQLException;

	/**
	 * 实施新增
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 * @throws SQLException
	 */
	protected abstract void doSaveInternal(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException, SQLException;
	/**
	 * 为创建新数据做准备
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 * @throws SQLException
	 */
	protected abstract void doCreateInternal(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException, SQLException;

	/**
	 * 实施数据的更新
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 * @throws SQLException
	 */
	protected abstract void doUpdateInternal(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException, SQLException;

	/**
	 * 为更新准备数据
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 * @throws SQLException
	 */
	protected abstract void doEditInternal(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException, SQLException;

	protected abstract void doDeleteInternal(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException, SQLException;

	protected abstract void doListInternal(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException,
			SQLException;


	/**
	 * 直接从request中取得同名的参数赋值给PageRequest对象<br>
	 * 有了PageRequest对象，就可以将其作为参数传递给相关的业务方法
	 * 
	 * @param query
	 * @param defaultSortColumns
	 *            制定排序字句 如“username desc [,age asc]”
	 * @param request
	 * @return
	 */
	public <T> void populateQuery(PageRequest<T> query,
			String defaultSortColumns, HttpServletRequest request) {
		try {
			Map<String, Object> parameterMap = ServletRequestUtils
					.getParametersStartingWith(request, "");
			// 拷贝属性
			beanUtils.copyProperties(query, parameterMap);
		} catch (IllegalAccessException e) {
			throw new IllegalArgumentException(
					"beanUtils.copyProperties() error", e);
		} catch (InvocationTargetException e) {
			throw new IllegalArgumentException(
					"beanUtils.copyProperties() error", e.getTargetException());
		}

		query.setPageNumber(ServletRequestUtils.getIntParameter(request,
				"pageNumber", 1));
		query.setPageSize(ServletRequestUtils.getIntParameter(request,
				"pageSize", BaseQuery.DEFAULT_PAGE_SIZE));
		String sortParameter = ServletRequestUtils.getStringParameter(request,
				"sortColumns", defaultSortColumns);//sortColumns  客户端的关于排序参数
		query.setSortColumns(sortParameter);

		// return query;
	}

	/**
	 * 
	 * @param page
	 *            要共享到下一个组件的page对象（里面有个列表）
	 * @param pageRequest
	 *            里面有页码等信息
	 * @param request
	 */
	public <T> void savePage(Page<T> page, PageRequest<T> pageRequest,
			HttpServletRequest request) {
		savePage("", page, pageRequest, request);
	}

	/**
	 * 用于一个页面有多个extremeTable是使用
	 * 
	 * @param tableId
	 *            等于extremeTable的tableId属性
	 */
	public <T> void savePage(String tableId, Page<T> page,
			PageRequest<T> pageRequest, HttpServletRequest request) {
//		page对象中主要是数据
		request.setAttribute(tableId + "page", page);
		request.setAttribute(tableId + "totalRows",
				new Integer(page.getTotalCount()));
		//将pageRequest对象也共享，供页面做状态的回显用
		request.setAttribute(tableId + "query", pageRequest);
	}
	@Override
	public void init(ServletConfig config) throws ServletException {
		// TODO Auto-generated method stub
		super.init(config);
		this.config = config;
	}
	protected List<String> upload(HttpServletRequest request, HttpServletResponse response, SmartUpload smartUpload, String basepath)
			throws ServletException, SmartUploadException, IOException {
				smartUpload.initialize(config, request, response);
				List<String> paths = new ArrayList<String>();
				java.io.File basePathFile = new java.io.File(basepath);
				if (!basePathFile.exists()) {
					basePathFile.mkdirs();
				}
				// 上传
				smartUpload.upload();
				for (int i = 0; i < smartUpload.getFiles().getCount(); i++) {
					File myfile = smartUpload.getFiles().getFile(i);
					String fileName = myfile.getFileName();
					fileName.replaceAll(",", "");//移除逗号
					// 保存
					String saveFilePath = basepath+fileName;
					myfile.saveAs(saveFilePath,SmartUpload.SAVE_PHYSICAL);
					paths.add(saveFilePath);
				}
				return paths;
			}
	protected ServletConfig config;
}
